import { useState, useRef, useEffect } from 'react'
import { useMouse, useMount } from 'ahooks';
import * as tf from '@tensorflow/tfjs';
import mjson from "./assets/tfjs_model/model.json?url";
// import reactLogo from './assets/react.svg'
// import viteLogo from '/vite.svg'
import './App.css'

function App() {
  // const [count, setCount] = useState(false);
  
  const cvs = useRef();
  const mouse = useMouse(cvs.current);
  /**
   * @type {CanvasRenderingContext2D}
   */
  let ctx
  /**
   * @type {tf.LayersModel}
   */
  let model;
  const [isMouseDown, setMouseDown] = useState(false);
  
  useEffect(() => {
    ctx = cvs.current?.getContext('2d')
    async function loadModel () {
      console.log(mjson)
      model = await tf.loadLayersModel(mjson);
      // model= tf.loadLayersModel()
    }
    loadModel();
  })
  // useMount(() => {
  //   ctx =
  // })

  const drawStart =() => {
    console.log("测试", ctx);
    ctx.moveTo(mouse.elementX, mouse.elementY);
    setMouseDown(true)
    // mouse.elementX
  }
  const drawing = () => {
    console.log ("fuck", ctx);
    if (isMouseDown) {
      ctx.lineTo(mouse.elementX, mouse.elementY);
      ctx.stroke()
    }
  }
  const test = () => {
    const img = new Image(28, 28);
    img.src = cvs.current.toDataURL()
    console.log(tf)
    const example = tf.FromPixels(img);  // for example
    const prediction = model.predict(example);
    console.log(prediction);
  }
  return (
    <>
      <p>在下方画布随便写个数字</p>
      <canvas
        ref={cvs} 
        width="28" 
        height="28"
        onMouseDown={drawStart}
        onMouseMove={drawing}
      ></canvas>
      <div>

      <button onClick={test}>识别</button>
      </div>
    </>
  )
}

export default App
